package cat.joronya.supermanager.europeo.privateleague;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.service.SearchPrivateLeagueHandler;
import cat.joronya.supermanager.europeo.service.SupermanagerServiceHelper;

/**
 * Activitat per cercar lligues privades per inscriure-s'hi.
 * @author pol
 */
public class SearchPrivateLeagueActivity extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_private_league);
    
		// amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeague.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeague.CONTENT_URI);
        }
	
        // inicialitzem amb l'array buit
        PrivateLeagueSearchAdapter adapter = 
        	new PrivateLeagueSearchAdapter(this, R.layout.search_private_league, new ArrayList<PrivateLeague>());
        setListAdapter(adapter);
	}
	
	public class PrivateLeagueSearchAdapter extends ArrayAdapter<PrivateLeague> 
	{
	    private ArrayList<PrivateLeague> items;
	    private Context context;

	    public PrivateLeagueSearchAdapter(Context context, int textViewResourceId, ArrayList<PrivateLeague> items) 
	    {
	        super(context, textViewResourceId, items);
	        this.context = context;
	        this.items = items;
	    }

	    public View getView(int position, View convertView, ViewGroup parent) 
	    {
	        View view = convertView;
	        if (view == null) {
	            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.search_private_league_row, null);
	        }

	        PrivateLeague item = items.get(position);
	        if (item!= null) 
	        {
	            // My layout has only one TextView
	            TextView itemView = (TextView) view.findViewById(R.id.private_league_search_row_name);
	            if (itemView != null) 
	            {
	                // do whatever you want with your string and long
	                itemView.setText(item.name);
	                itemView.setTag(item.id);
	            }
	         }

	        return view;
	    }
	}
	
	public void searchPrivateLeagueWithText(View view) 
	{
    	// get serch input value
		EditText searchText = (EditText)findViewById(R.id.private_league_search_input);
		String search = searchText.getText().toString();
    	Log.d(TAG,"searchPrivateLeagueWithText search: "+search);
    	
    	// ocultem el teclat
    	InputMethodManager imm = (InputMethodManager)getSystemService(
    		      Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
    	
		// mostrem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
        progressBar.setVisibility(View.VISIBLE);
        
        // toast de cerca iniciada
        Toast.makeText(this, R.string.private_league_search_join_launched, Toast.LENGTH_SHORT).show();
        
    	// arranquem el service amb el helper
		SupermanagerServiceHelper.getInstance(SearchPrivateLeagueActivity.this).searchPrivateLeagueWithText(handler, search);
	}
	
	public void searchPrivateLeagueWithGroup(View view)
	{
		String group = view.getTag().toString();
		Log.d(TAG, "searchPrivateLeagueWithGroup group: "+group);
    	
		// borrem texte de possible cerca anterior per texte
		EditText searchText = (EditText)findViewById(R.id.private_league_search_input);
		searchText.setText("");
		
		// mostrem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
        progressBar.setVisibility(View.VISIBLE);
        
        // toast de cerca iniciada
        Toast.makeText(this, R.string.private_league_search_join_launched, Toast.LENGTH_SHORT).show();
        
		// arranquem el service amb el helper
		SupermanagerServiceHelper.getInstance(SearchPrivateLeagueActivity.this).searchPrivateLeagueWithGroup(handler, group);	
	}
	
	/**
	 * Al clicar una lliga privada anem al detall.
	 */
	protected void onListItemClick (ListView l, View v, int position, long id)
	{
		int idpri = 0;
		String name = "";
		try
		{
			TextView textView = (TextView)v.findViewById(R.id.private_league_search_row_name);
			idpri = Integer.parseInt(textView.getTag().toString());
			name = textView.getText().toString();
		}catch(Exception e){}
		
		Log.d(TAG,"inscribint a lliga privada id_pri: "+idpri);
		
		// al click, mostrar activity demanant password i boto join
		startActivity(new Intent(this,JoinPrivateLeagueActivity.class)
		.setData(Supermanager.PrivateLeague.CONTENT_URI)
		.putExtra("cat.joronya.supermanager.europeo.privateleagues.id_pri", idpri)
		.putExtra("cat.joronya.supermanager.europeo.privateleagues.name", name));
	}
	
	SearchPrivateLeagueHandler handler = new SearchPrivateLeagueHandler()
	{

		@SuppressWarnings("unchecked")
		@Override
		public void searchOk(Message msg) 
		{
			// amaguem el ProgressBar
	        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
	        progressBar.setVisibility(View.INVISIBLE);			
	        
	        // populate list with search results
	        ArrayList<PrivateLeague> privateLeagues = (ArrayList<PrivateLeague>)
	        	msg.getData().getSerializable(Supermanager.PRIVATE_LEAGUE_SEARCH_RESULTS);
	        
	        // inicialitzem amb l'array trobat
	        PrivateLeagueSearchAdapter adapter = 
	        	new PrivateLeagueSearchAdapter(SearchPrivateLeagueActivity.this, R.layout.search_private_league_row, privateLeagues);
	        setListAdapter(adapter);
		}

		@Override
		public void authError() 
		{
			// amaguem el ProgressBar
	        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
	        progressBar.setVisibility(View.INVISIBLE);
	        
	        // mostrem error
	        Toast.makeText(SearchPrivateLeagueActivity.this, R.string.private_league_search_auth_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void otherError() 
		{
			// amaguem el ProgressBar
	        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
	        progressBar.setVisibility(View.INVISIBLE);			
	        
	        // mostrem error
	        Toast.makeText(SearchPrivateLeagueActivity.this, R.string.private_league_search_other_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void connectivityError() 
		{
			// amaguem el ProgressBar
	        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_search_loading);
	        progressBar.setVisibility(View.INVISIBLE);			
	        
	        // mostrem error
	        Toast.makeText(SearchPrivateLeagueActivity.this, R.string.private_league_search_connectivity_error, Toast.LENGTH_LONG).show();
		}
	};

}
